import { MESSAGE_INFO_ICON } from "../Config/message-type-icon";
import { MESSAGE_ERROR_ICON } from "../Config/message-type-icon";
import { MESSAGE_SUCCESS_ICON } from "../Config/message-type-icon";
import { MESSAGE_WARNING_ICON } from "../Config/message-type-icon";

/**
 * 全局消息提示组件 类似 ElementPlus ElMessage
 */
type IMessageOptions = { duration?: number; appendTo?: string | HTMLElement };

/**
 * 全局消息提示组件
 * @param text 显示文本
 * @param options 配置项
 *   @ duration?: number  显示时间，单位为毫秒，默认为 3000,当把这个属性的值设置为0便表示该消息不会被自动关闭
 *   @ appendTo?: string | HTMLElement 提示的挂载位置，默认为 body
 * @example
 *    const message = this.message.warn("测试", { duration: 0 });
 *    setTimeout(() => message.close(), 3000);
 */
export class Message {
  constructor() {}

  private createDom(appendTo?: string | HTMLElement) {
    const box = document.querySelector(".konva-root-message-box");
    if (box) return box;
    const messageBox = document.createElement("div");
    messageBox.className = "konva-root-message-box";

    // 判断 appendTo 类型
    if (typeof appendTo === "string") {
      const appendToElement = document.querySelector(appendTo);
      if (appendToElement) appendToElement.appendChild(messageBox);
    } else if (appendTo instanceof HTMLElement) {
      appendTo.appendChild(messageBox);
    } else {
      document.body.appendChild(messageBox);
    }

    return messageBox;
  }

  private removeDom(dom: HTMLDivElement, payload?: IMessageOptions) {
    // 解析参数
    const { duration = 3000 } = payload || {};

    if (duration === 0) return;

    const t = setTimeout(() => {
      clearTimeout(t);
      dom.remove();
      // 取 konva-root-message-box children
      const messageBox = document.querySelector(".konva-root-message-box")!;
      const children = messageBox.children;
      if (children.length === 0) messageBox.remove();
    }, duration);
  }

  public success(text: string, payload?: IMessageOptions) {
    const content = `${MESSAGE_SUCCESS_ICON} ${text}`;
    return this.showMessage(content, payload);
  }

  public error(text: string, payload?: IMessageOptions) {
    const content = `${MESSAGE_ERROR_ICON} ${text}`;
    return this.showMessage(content, payload);
  }

  public info(text: string, payload?: IMessageOptions) {
    const content = `${MESSAGE_INFO_ICON} ${text}`;
    return this.showMessage(content, payload);
  }

  public warn(text: string, payload?: IMessageOptions) {
    const content = `${MESSAGE_WARNING_ICON} ${text}`;
    return this.showMessage(content, payload);
  }

  private showMessage(content: string, payload?: IMessageOptions) {
    const box = this.createDom(payload?.appendTo);
    const messageBox = document.createElement("div");
    messageBox.innerHTML = content;
    box.appendChild(messageBox);

    // 判断当前传入的 message 是否自动关闭
    this.removeDom(messageBox, payload);

    // Message 方法
    // close 关闭当前的 Message
    return {
      close: () => this.removeDom(messageBox, { duration: 0.1 }),
    };
  }
}
